package com.heima.wemedia.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    WmNewsMapper wmNewsMapper;
    @Autowired
    WmUserMapper wmUserMapper;
    @Autowired
    WmChannelMapper wmChannelMapper;
    @Qualifier("com.heima.apis.article.IArticleClient")
    @Autowired
    private IArticleClient articleClient;
    @Autowired
    Tess4jClient tess4jClient;

    @Override
    @Async
    public void autoScanWmNews(Integer id) {
        //1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null)
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        if (WmNews.Status.SUBMIT.getCode() == wmNews.getStatus()) {
            //从内容中提取纯文本内容和图片
            Map<String, Object> textAndImages = HandleTextAndImages(wmNews);
            //自管理的敏感词过滤
            boolean isSensitive = handleSensitiveScan((String) textAndImages.get("content"), wmNews);
            if (!isSensitive) return;
            //2.审核文本内容  阿里云接口
            boolean isTextScan = handleTextScan((String) textAndImages.get("text"), wmNews);
            if (!isTextScan) return;
            //3.审核图片  阿里云接口
            boolean isImageScan = HandleImageScan((List<String>) textAndImages.get("images"), wmNews);
            if (!isImageScan) return;
            //4.审核成功，保存app端的相关的文章数据
            ResponseResult responseResult = saveArticle(wmNews);
            if (!responseResult.getCode().equals(200)) {
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
            }
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews, (short) 9, "审核成功");
        }


    }

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    /**
     * 自管理的敏感词审核
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        if (StrUtil.isEmpty(content)) return true;
        boolean flag = true;

        //获取所有的敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);

        //查看文章中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0) {
            updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容" + map);
            flag = false;
        }
        return flag;
    }

    /**
     * 保存app端相关的文章数据
     *
     * @param wmNews
     */
    private ResponseResult saveArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null)
            dto.setAuthorName(wmUser.getName());
        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null)
            dto.setChannelName(wmChannel.getName());
        //文章的布局
        dto.setLayout(wmNews.getType());
        dto.setCreatedTime(new Date());
        return articleClient.saveArticle(dto);
    }

    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private GreenImageScan greenImageScan;

    /**
     * 审核图片
     *
     * @param images
     * @param wmNews
     * @return
     */
    private boolean HandleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        if (CollUtil.isEmpty(images))
            return flag;
        //图片去重
        images = images.stream().distinct().collect(Collectors.toList());
        ArrayList<byte[]> imageList = new ArrayList<>();
        try {
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);
                //byte数组转换为BufferedImage
                ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
                BufferedImage bufferedImage = ImageIO.read(inputStream);
                //识别图片文字
                String result = tess4jClient.doOCR(bufferedImage);
                boolean isSensitive = handleSensitiveScan(result, wmNews);
                if (!isSensitive) return false;
                imageList.add(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
//            Map map = greenImageScan.imageScan(imageList);
            Map map = new HashMap();
            //审核失败
            if ("block".equals(map.get("suggestion"))) {
                flag = false;
                updateWmNews(wmNews, (short) 2, "当前图片中存在违规内容");
            }
            //不确定信息  需要人工审核
            if ("review".equals(map.get("suggestion"))) {
                flag = false;
                updateWmNews(wmNews, (short) 3, "当前图片中存在不确定内容");
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 审核文本内容
     *
     * @param text
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String text, WmNews wmNews) {
        boolean flag = true;
        if (text.length() == 0) {
            return flag;
        }
        try {
            Map map = greenTextScan.greeTextScan(text);
            if (map != null) {
                //审核失败
                if ("block".equals(map.get("suggestion"))) {
                    flag = false;
                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
                }
                //不确定信息  需要人工审核
                if (map.get("suggestion").equals("review")) {
                    flag = false;
                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 修改文章内容
     *
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 从内容中提取纯文本内容和图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> HandleTextAndImages(WmNews wmNews) {
        StringBuilder text = new StringBuilder();
        List<String> images = new ArrayList<>();
        String content = wmNews.getContent();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if ("text".equals(map.get("type")))
                text.append((String) map.get("value"));
            else if ("image".equals(map.get("type")))
                images.add((String) map.get("value"));
        }
        images.addAll(Arrays.asList(wmNews.getImages().split(",")));
        text.append(wmNews.getTitle());
        Map<String, Object> textAndImages = new HashMap<>();
        textAndImages.put("text", text.toString());
        textAndImages.put("images", images);
        return textAndImages;
    }
}
